<template>
  <view class="membership-page">
    <view class="top-card">
      开通会员平均省￥600/年>
    </view>
    <view class="gold-card">
      <view class="card-title-container">
        <view class="line"></view>
        <view class="card-title">专属6大权益</view>
        <view class="line"></view>
      </view>
      <view class="small-cards-container">
        <view class="small-card">
          <view class="card-tag">免运费</view>
          <view class="card-item-title">满39元</view>
          <view class="card-item-content">主城区包邮</view>
        </view>
        <view class="small-card">
          <view class="card-tag">福利</view>
          <view class="card-item-title">积分</view>
          <view class="card-item-content">注册赠送2000</view>
        </view>
        <view class="small-card">
          <view class="card-tag">抽奖</view>
          <view class="card-item-title">神秘礼品</view>
          <view class="card-item-content">注册即可抽奖</view>
        </view>
        <view class="small-card">
          <view class="card-tag">抽奖</view>
          <view class="card-item-title">超级省</view>
          <view class="card-item-content">积分盲盒天天领</view>
        </view>
        <view class="small-card">
          <view class="card-tag">活动</view>
          <view class="card-item-title">热门商品</view>
          <view class="card-item-content">积分秒杀</view>
        </view>
        <view class="small-card">
          <view class="card-tag">免费</view>
          <view class="card-item-title">美食品鉴</view>
          <view class="card-item-content">特邀免费品尝</view>
        </view>
      </view>
    </view>
    <view class="gold-card details-card">
      <view class="card-title-container">
        <view class="line"></view>
        <view class="card-title">权益详情</view>
        <view class="line"></view>
      </view>
      <!-- 这里可以添加权益详情的具体内容 -->
      <view style="padding: 20px; color: #522F0C;">
        <text>这里是权益详情的具体内容，您可以根据需要添加文本、图片或其他组件。</text>
      </view>
    </view>
        <view class="bottom-button-wrapper">
          <button class="join-vip-button" @click="openMembership">
            <text class="price-text">￥99/年</text>
            <text class="action-text">立即开通</text>
          </button>
        </view>
        <payment :pay_close="pay_close" @onChangeFun="onChangeFun" :order_id="order_id" :totalPrice="totalPrice" :payMode="payMode"></payment>
      </view>
    </template>
    
    <script>
    import { getUserInfo } from '@/api/user.js';
    import { getAddressList } from '@/api/user.js';
    import { preOrderApi, orderCreate } from '@/api/order.js';
    import payment from '@/components/payment/index.vue';
    
    export default {
      name: 'MembershipPage',
      components: {
        payment
      },
      data() {
        return {
          userInfo: {
            avatar: '',
            nickname: '',
            level: 0,
          },
          pay_close: false,
          payMode: [
            {
              name: '微信支付',
              icon: 'icon-weixinzhifu',
              value: 'weixin',
              title: '微信快捷支付',
            },
            {
              name: '余额支付',
              icon: 'icon-yuezhifu',
              value: 'yue',
              title: '可用余额:',
              number: 0,
            },
          ],
          order_id: '',
          totalPrice: '99',
        };
      },
      onLoad() {
        uni.setNavigationBarTitle({
          title: '会员权益'
        });
        this.fetchUserInfo();
      },
      methods: {
        onChangeFun: function(e) {
          let that = this;
          switch (e.action) {
            case 'payClose':
              this.pay_close = false;
              break;
            case 'pay_complete':
              this.pay_close = false;
              uni.showToast({
                title: '支付成功',
                icon: 'success'
              });
              that.fetchUserInfo();
              break;
            case 'pay_fail':
              this.pay_close = false;
              uni.showToast({
                title: '支付失败',
                icon: 'none'
              });
              break;
          }
        },
        fetchUserInfo() {
          return new Promise((resolve, reject) => {
            getUserInfo().then(res => {
              this.userInfo = res.data;
              this.payMode[1].number = res.data.nowMoney;
              resolve(res.data);
            }).catch(err => {
              reject(err);
            });
          });
        },
                openMembership() {
                  (this.userInfo.nickname ? Promise.resolve() : this.fetchUserInfo()).then(() => {
                    getAddressList().then(addressRes => {
                      if (!addressRes.data.list.length) {
                        uni.showModal({
                          title: '提示',
                          content: '请先添加您的地址信息',
                          success: (res) => {
                            if (res.confirm) {
                              uni.navigateTo({
                                url: '/pages/users/user_address_list/index'
                              });
                            }
                          }
                        });
                      } else {
                        let defaultAddress = addressRes.data.list.find(item => item.isDefault) || addressRes.data.list[0];
                        this.createMembershipOrder(defaultAddress.id, defaultAddress.realName, defaultAddress.phone);
                      }
                    });
                  });
                },
                        createMembershipOrder(addressId, realName, phone) {
                          if (!this.userInfo.nickname) {
                            return this.$util.Tips({
                              title: '用户信息获取失败，请稍后重试'
                            });
                          }
                          const orderDetails = [{
                            productId: 185, // 年度VIP会员商品ID
                            attrValueId: 906, // 对应的 eb_store_product_attr_value.id
                            productNum: 1,
                          }];
                
                          preOrderApi({
                            "preOrderType": "buyNow",
                            "orderDetails": orderDetails
                          }).then(res => {
                            const preOrderNo = res.data.preOrderNo;
                            orderCreate({
                              preOrderNo: preOrderNo,
                              payType: 'weixin', // Default to weixin, will be updated by payment component
                              from: 'routine',
                              shippingType: "2",
                              addressId: "0",
                              useIntegral: 0,
                              couponId: 0,
                              mark: "购买年度会员",
                              payChannel: "routine",
                              realName: realName,
                              phone: phone,
                              storeId: 0
                            }).then(res => {              this.order_id = res.data.orderNo;
              this.pay_close = true;
            }).catch(err => {
              console.error('Order create failed. Error object:', err);
              let errorMessage = '订单创建失败';
              if (typeof err === 'string') {
                errorMessage = err;
              } else if (err && err.message) {
                errorMessage = err.message;
              }
              uni.showToast({
                title: errorMessage,
                icon: 'none'
              });
            });
          }).catch(err => {
            console.error('Pre-order failed. Error object:', err);
            let errorMessage = '预下单失败';
            if (typeof err === 'string') {
              errorMessage = err;
            } else if (err && err.message) {
              errorMessage = err.message;
            }
            uni.showToast({
              title: errorMessage,
              icon: 'none'
            });
          });
        }
      }
    }
    </script>

<style lang="scss" scoped>
.membership-page {
  display: flex;
  flex-direction: column; /* Changed to column to stack card and button */
  justify-content: flex-start; /* Push content to top */
  align-items: center;
  min-height: 100vh; // Take full viewport height
  background-color: #f0f2f5; // A neutral background for the page
  padding-bottom: 80px; /* Add padding for the fixed button wrapper */
}

.top-card {
  width: 85%;
  max-width: 550px;
  background: linear-gradient(to left, #E4B98F, #F9EAD8); /* 更深的金色渐变 */
  border-radius: 15px;
  padding: 25px 20px; /* 增加高度 */
  text-align: center;
  color: #522F0C; /* 深棕色文字 */
  font-size: 16px;
  font-weight: bold;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  margin-top: 20px; /* 距离页面顶部 */
  margin-bottom: -20px; /* 负边距，使gold-card重叠，露出更多top-card */
  z-index: 1;
}

.gold-card {
  position: relative;
  width: 90%;
  max-width: 600px;
  background: linear-gradient(to bottom, #FFF3E7, #FFEDDC); /* 渐变背景色 */
  border-radius: 20px; /* Keep for bottom corners */
  clip-path: polygon(0% 0%, 50% 15px, 100% 0%, 100% 100%, 0% 100%); /* 两边高，中间低，凹陷更浅 */
  padding: 80px 20px 30px 20px; /* Increased padding-top to push content down further */
  
  text-align: center;
  /* margin-top removed as top-card handles spacing */
  margin-bottom: 15px; /* Space between card and button */
  z-index: 2;
}

.details-card {
  background: linear-gradient(to bottom, #FFFFFF, #FBFBFB); /* 新卡片的渐变背景色 */
}

.card-title-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  margin-top: 15px; /* Reset margin-top as padding controls position now */
}

.card-title {
  font-size: 18px; /* 字体再小一点 */
  font-weight: bold;
  color: #522F0C; /* 深棕色，与金色搭配 */
  margin: 0 15px; /* Space between text and lines */
}

.line {
  flex-grow: 1;
  height: 1px; /* 细横线 */
  max-width: 50px; /* 短一点 */
  background: linear-gradient(to right, #E0C28C, #FADFAD); /* 渐变 */
}

.line:last-child {
  background: linear-gradient(to left, #E0C28C, #FADFAD); /* 右侧线反向渐变 */
}

.small-cards-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  gap: 15px; /* Space between small cards */
}

.small-card {
  width: 120px;
  height: 120px;
  background: linear-gradient(to bottom, #FDE2C5, #FAD5B0); /* 小卡片渐变背景色 */
  border-radius: 15px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column; /* To stack title and content */
  justify-content: center;
  align-items: center;
  color: #fff; /* Placeholder for text inside small cards */
  font-size: 18px;
  font-weight: bold;
  position: relative; /* Added for positioning the tag */
  /* You can add content or icons here later */
}

.card-item-title {
  font-size: 16px;
  font-weight: bold;
  color: #8B4513; /* 深棕色 */
  margin-bottom: 5px;
}

.card-item-content {
  font-size: 14px;
  color: #A0522D; /* 稍浅的棕色 */
}

.card-tag {
  position: absolute;
  top: 0;
  left: 0;
  background-color: #CB8644; /* 深色半透明背景 */
  color: #fff;
  font-size: 12px;
  padding: 2px 8px;
  border-top-left-radius: 15px; /* 与小卡片圆角匹配 */
  border-bottom-right-radius: 8px; /* 右下角稍微圆角 */
  z-index: 10;
}

.bottom-button-wrapper {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  padding: 10px 0; /* Padding for the wrapper */
  background: linear-gradient(to bottom, #FFF9F1, #FFF7EE); /* 渐变背景色 */
  display: flex;
  justify-content: center; /* Center the button horizontally */
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05); /* Subtle shadow */
  z-index: 99; /* Ensure it's below the button's z-index if needed */
}

.join-vip-button {
  position: relative; /* Keep relative for pseudo-element */
  width: 90%; /* Make it wide */
  max-width: 400px; /* Example max-width */
  background: linear-gradient(to left, #E3BA8F, #F0D5B8); /* 右侧渐变背景 */
  border: none;
  border-radius: 25px; /* Restore border-radius */
  padding: 20px 30px; /* Increased padding for height */
  font-size: 18px;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s ease;
  overflow: hidden; /* Crucial for pseudo-element clipping */
  display: flex; /* Use flex to center content */
  justify-content: space-between; /* Space out the two text elements */
  align-items: center;
  z-index: 100; /* Ensure button is on top of other content */
}

.join-vip-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 60%; /* Adjust to control dark area width */
  height: 100%;
  background: linear-gradient(to left, #57320D, #87581B); /* Dark side gradient */
  z-index: 1;
}

.price-text {
  position: relative; /* Relative to button, but z-index works */
  z-index: 2; /* Ensure text is above pseudo-element */
  color: #FFF3E7; /* Text color for dark side */
  width: 60%; /* Occupy the left 60% */
  text-align: center;
}

.action-text {
  position: relative; /* Relative to button, but z-index works */
  z-index: 2; /* Ensure text is above pseudo-element */
  color: #522F0C; /* Text color for light side */
  width: 40%; /* Occupy the right 40% */
  text-align: center;
}

.join-vip-button:active {
  background-color: #DAA520; /* 点击时的深金色 */
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .gold-card {
    width: 95%;
    padding: 20px 15px;
  }
  .card-title {
    font-size: 18px; /* Adjust for smaller screens */
  }
  .small-card {
    width: 100px;
    height: 100px;
  }
  .join-vip-button {
    font-size: 16px;
    padding: 15px 25px; /* Adjusted padding for height on smaller screens */
  }
}
</style>